<!--使用elementUI封装 table组件 类antDesign pro的Stable-->
<!-- copy from warroom -->
<!-- 添加
    1.可在columns中配置点击事件，并为其增加 class = click__div 
    2.可配置2级表头
   -->
<template>
  <div class="hedait-table" v-loading="isLoading">
    <el-table
      :data="tableData.data"
      :border="border"
      ref="tableComponent"
      @sort-change="sortChange"
      :row-key="$attrs['row-key'] || 'id'"
      v-bind="$attrs"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="selectionCol" v-bind="selectionCol" />
      <TableColumns v-for="(item, index) in showColumns" :key="index" v-bind="item">
        <!-- <template v-if="item.slots" #[item.slots]="data"> -->
          <!-- <component :is="$slots[item.slots]" v-if="item.slots"></component> -->
        <!-- </template> -->
        <template
          v-for="(slot, slotName) in $slots"
          :key="slotName"
          #[slotName]="{[slotName]: data}"
        >
          <slot :name="slotName" :[slotName]="data"/>
        </template>
      </TableColumns>
    </el-table>
    <Toolbar class="pageStyle" :style="pageStyle">
      <template #left>
        <slot name="footer" />
      </template>
      <el-pagination
        :class="pageClass"
        v-if="showPagination"
        :background="true"
        :layout="pagination.layout"
        :current-page="tableData.pageParam.page"
        :total="tableData.pageParam.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </Toolbar>
  </div>
</template>


<script lang="ts">
//默认选中没处理
import _ from "lodash";
import { ref, computed, onMounted, nextTick, reactive, toRaw } from "vue";
import TableColumns from "./TableColumns.vue";
import Toolbar from '../../toolbar/src/Toolbar.vue';
// import '@jimu/ui/console/src/types/table.d.ts'

interface jimuTableData {
  records: any[],
  page: number,
  total: number,
  rows: number
}

interface tabelParam {
  total?: number;
  page: number;
  rows: number;
}

export default {
  name: 'JimuTable',
  components: { TableColumns, Toolbar },
  inheritAttrs: false,
  props: {
    columns: {
      type: Array,
    },
    data: {
      type: Function,
      // default: () => (function(){return new Promise(()=>{})}),
    },
    pageClass: {
      type: String,
      default: "",
    },
    showPagination: {
      type: Boolean,
      default: true,
    },
    border: {
      type: Boolean,
      default: true,
    },
    isSelection: {
      type: Boolean,
      default: false,
    },
    autoload: {
      type: Boolean,
      default: false,
    },
    pagination: {
      type: Object,
      default: () => {
        return {layout: "prev, pager, next,total, jumper, sizes"}
      },
    },
    pageStyle: {
      type: Object,
      default: () => ({}),
    },
  },
  mounted(){
    console.log('table', (this as any).$slots)
  },
  setup(props:any, { attrs }:any) {
    

    const showColumns = computed(() => {
      return props?.columns?.filter(
        (item: any) => item.isShow !== false && item?.type !== "selection"
      );
    });

    const selectionCol:any = computed<any>(() => {
      let list = props?.columns?.filter(
        (item: any) => item.type === "selection"
      );
      return list && list.length > 0 ? list[0] : null;
    });

    const tableComponent:any = ref(null);

    const pageParam: tabelParam = {
      rows: 10,
      total: 0,
      page: 1,
    };

    const tableData:any = reactive({
      pageParam,
      data: [],
      sort: {},
      selectionCol:[]
    });

    const isLoading = ref(true);

    const refresh = (isFirstPage?: boolean) => {
      //更新 isFirstPage true返回第一页
      tableData.pageParam.page = isFirstPage ? 1 : tableData.pageParam.page;
      let param: tabelParam = Object.assign(
        tableData.sort,
        tableData.pageParam
      );
      delete param.total;
      isLoading.value = true;

      props?.data(toRaw(param)).then((res: jimuTableData) => {
        console.log('res: ', res);
        isLoading.value = false;
        //  let resData = res?.data
        // if (res) {
        //   tableData.data = res.records;
        // } else {
        //   tableData.data = [];
        // }
        tableData.data = res?.records || [];

        tableComponent.value.clearSelection()

        //处理formatter
        // let formatter: any = {};
        // props.columns?.forEach((item: any) => {
        //   if (item.formatter) {
        //     formatter[item.prop] = item.formatter;
        //   }
        // });

        //默认选中处理
        nextTick(() => {
          // if(this.selectionCol && this.selectionCol.check){
          tableData.data.forEach((row:any, index:number) => {
            if (
              selectionCol.value &&
              selectionCol.value?.check &&
              selectionCol.value.check(row, index)
            ) {
              tableComponent.value.toggleRowSelection(row, true);
            }
            for (let key of _.intersection(
              // Object.keys(formatter),
              Object.keys(row)
            )) {
              // row[key] = formatter[key].call(this, row[key]);
            }
          });
          // }
        });

        if (props.showPagination) {
          tableData.pageParam = {
            rows: res.rows || tableData.pageParam.rows,
            page: res.page || tableData.pageParam.page,
            total: res.total || tableData.pageParam.total,
          };
        }

        // tableComponent.value.doLayout();
      }).catch((error:any)=>{
        console.error('table 加载数据时报错！', error)
        isLoading.value = false;

      });
    };

    const sortChange = ({ column, prop }:any) => {
      if (!attrs["onSortChange"]) {
        //点击排序
        tableData.sort = {
          sortName: prop,
          sort: column.order == "descending" ? "desc" : "asc",
        };
        refresh(true);
      }
    };

    const handleSelectionChange = (val:any) => {
      tableData.selectionCol = val
    }

    const handleCurrentChange = (value: number) => {
      //改变当前页
      tableData.pageParam.page = value;

      refresh();
    };

    const handleSizeChange = (value: number) => {
      tableData.pageParam = {
        page: 1,
        rows: value,
        total: 0,
      };
      refresh();
    };

    const getSelectCols = ()=>{
      return tableData.selectionCol
    }

    onMounted(() => {
      props.autoload && refresh(true);
    });

    return {
      tableData,
      isLoading,
      selectionCol,
      showColumns,
      refresh,
      handleCurrentChange,
      handleSizeChange,
      sortChange,
      tableComponent,
      handleSelectionChange,
      getSelectCols,
    };
  },
};
</script>

<style lang="scss" scoped>
.hedait-table {
  display: flex;
  flex-direction: column;
  align-items: center;
  // margin-top: 10px;

  .el-table {
    color: #575b72;
  }

  :deep(.hedait-table_header) {
    // background-color: #EAF8F7 !important;
    &:deep(th),
    &:deep(tr) {
      background-color: transparent;
      color: #323653;
    }
  }

  .pageStyle {
    margin: 20px 0;
    width: 100%;
    display: flex;
    justify-content: center;
  }
}
.click__div {
  color: #409eff;
  cursor: pointer;
}
.el-table :deep(th) {
  background: #f5f7fa;
}
</style>